package com.zrrd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zrrd.reggie.bean.Dish;
import com.zrrd.reggie.bean.Flavor;
import com.zrrd.reggie.bean.dto.DishDto;
import com.zrrd.reggie.mapper.DishMapper;
import com.zrrd.reggie.service.DishService;
import com.zrrd.reggie.service.FlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private FlavorService flavorService;

    @Override
    @Transactional
    public void saveDish(DishDto dto) {
        //给菜品设置一个排序
        dto.setSort(1);
        //将菜品的基本信息保存到菜品表
        this.save(dto);
        //获取dto对象中的口味集合
        List<Flavor> flavors = dto.getFlavors();
        //遍历集合
        for (Flavor flavor : flavors) {
            //给口味对象设置所属菜品id
            flavor.setDishId(dto.getId());
        }
        //批量保存口味
        flavorService.saveBatch(flavors);
    }

    //修改时展示菜品信息
    @Override
    public DishDto getDishWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishDto dto = new DishDto();
        BeanUtils.copyProperties(dish, dto);
        QueryWrapper<Flavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id", id);
        List<Flavor> flavors = flavorService.list(wrapper);
        dto.setFlavors(flavors);
        return dto;
    }


    //修改菜品
    @Override
    @Transactional
    public boolean updateDish(DishDto dto) {
        boolean a = this.updateById(dto);
        QueryWrapper<Flavor> wrapper = new QueryWrapper<>();
        wrapper.eq("dish_id", dto.getId());
        flavorService.remove(wrapper);
        List<Flavor> flavors = dto.getFlavors();
        for (Flavor flavor : flavors) {
            flavor.setDishId(dto.getId());
        }
        boolean b = flavorService.saveBatch(flavors);
        return a && b;
    }

}
